package com.dailyyoga.bitmapManager;

import com.dailyyoga.view.RecyclingImageView;
import com.tools.BitmapUtile;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;

public class SdcardImageLoader extends YogaImageLoader {

	int mW;
	int mH;
	int mOffset = 0;

	public SdcardImageLoader(Context context, int w, int h) {
		super(context);
		mW = w;
		mH = h;

	}

	public void downLoad(String key, RecyclingImageView imageView,
			int defultIcon) {
		Log.d("SdcardImageLoader", "url=" + key);
		mOffset = key.length();
		RecyclingBitmapDrawable bitmap = getBitmapFromCache(key + "mW_" + mW
				+ "mH_" + mH);
		if (null != bitmap) {
			imageView.setImageDrawable(bitmap);
			imageView.setCachePath(key);

			cancleFile(key, imageView); // 取消下载
			return;
		}

		if (defultIcon != mDefault) {
			mBuffBitmap = BitmapFactory.decodeResource(mContext.getResources(),
					defultIcon);
			mDefault = defultIcon;
		}

		if (key.contains("tou.jpg") || key.contains("tou2.jpg")
				|| key.contains("tou1.jpg")) {

			imageView.setImageBitmap(mBuffBitmap);

		} else if (cancleFile(key, imageView)) { // 没有任务进行。，。。开始下载

			Log.d("SdcardImageLoader", "ImageFileTask=" + key);
			ImageFileTask task = new ImageFileTask(imageView);
			FileImage zhanwei_image = new FileImage(task, mBuffBitmap);
			imageView.setImageDrawable(zhanwei_image);
			task.execute(key);
		}
	}

	public SdcardImageLoader(Context context) {
		super(context);
	}

	protected RecyclingBitmapDrawable getBitmapFromFile(String path) {
		Log.d("getBitmapFromFile", "getBitmapFromFile=" + path);
		try {
			Bitmap bitmap = getThumbIcon(path.substring(0, mOffset));
			RecyclingBitmapDrawable bitmapDrawable = new RecyclingBitmapDrawable(
					mContext.getResources(), bitmap);
			bitmapDrawable.setIsCached(true);
			return bitmapDrawable;

		} catch (Exception e) {

			e.printStackTrace();
			return null;
		}

	}

	private Bitmap getThumbIcon(String path) {
		BitmapUtile bitmapUtile = BitmapUtile.getBitmapUtile();
		return bitmapUtile.decodeBitmap(path, mW, mH);
	}
}
